package com.captjack.micro.web.admin.controller;

import com.captjack.micro.api.base.BaseController;
import com.captjack.micro.api.hello.MicroServiceOne;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.UUID;

/**
 * @author Capt Jack
 * @date 2018/3/7
 */
@RestController
@RequestMapping(value = "/hello", method = {RequestMethod.GET, RequestMethod.POST})
public class TestController extends BaseController {

    /**
     * 日志
     */
    private static final Logger logger = LoggerFactory.getLogger(TestController.class);

    /**
     * feign 声明式调用微服务
     */
    private final MicroServiceOne microServiceOne;

    /**
     * 从配置中心读取的配置
     */
    @Value("${version}")
    private String version;

    @RequestMapping("/hello")
    @HystrixCommand(fallbackMethod = "test")
    public String hello() {
        try {
            String result = microServiceOne.service(1, 2);
            // 发送邮件
            return this.version + "===" + result;
        } catch (Exception e) {
            logger.error("hello error! cause by : ", e);
            return null;
        }
    }

    private String test() {
        return "safasg";
    }

    @RequestMapping(value = "")
    public String test1() {
        return UUID.randomUUID().toString();
    }

    /**
     * 直接以url形式调用
     *
     * @return 调用结果
     */
    private Object restInvoke() {
        // 请求参数
        MultiValueMap<String, Object> postParams = new LinkedMultiValueMap<>();
        postParams.add("num1", 15);
        postParams.add("num2", 30);
        // ribbon 形式调用微服务
        return getRestTemplate().postForObject(MicroServiceOne.SERVICE_URL, postParams, String.class, postParams);
    }

    @Override
    protected void service() {

    }

    @Autowired
    public TestController(MicroServiceOne microServiceOne) {
        this.microServiceOne = microServiceOne;
    }

}
